<template>
  <div class="dashboard-container">
    <el-card>

      <!-- //^提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
      />

      <!-- //^下拉选择 -->
      <el-row class="cascader">
        <span>选择商品分类：</span>
        <!--
            v-model(设置级联菜单绑定数据)

            :props(用来配置数据显示的规则)
            props.expandTrigger可以定义展开子级菜单的触发方式
            props.checkStrictly = true 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的

            :options(指定级联菜单数据源)
            clearable(提供“X”号完成删除文本功能)
           -->
        <el-cascader
          v-model="selectedKeys"
          :options="attributesList"
          :props="props"
          clearable
          @change="handleChange"
        />
      </el-row>

      <!-- //^tab面板 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- //#动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" style="margin-bottom: 15px" @click="addDialogVisible=true">添加参数</el-button>

          <!-- 动态参数表格 -->
          <!--:data="manyTableData" 显示的数据-->
          <!--border 是否带有纵向边框-->
          <!--stripe 是否为斑马纹 table-->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable class="tag" @close="handleClose(index, scope.row)">{{ item }}</el-tag>
                <!-- 输入的文本框 -->
                <el-input v-if="scope.row.inputVisible" ref="saveTagInput" v-model="scope.row.inputValue" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" />
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#" />
            <!--label="参数名称" 显示的标题-->
            <!--prop="attr_name"对应列内容的字段名-->
            <el-table-column label="参数名称" prop="attr_name" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="alterAttributes(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delAttributes(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- //#静态属性  -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加参数的按钮 -->
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" style="margin-bottom: 15px" @click="addDialogVisible=true">添加属性</el-button>

          <!-- 动态参数表格 -->
          <!--:data="onlyTableData" 显示的数据-->
          <!--border 是否带有纵向边框-->
          <!--stripe 是否为斑马纹 table-->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable class="tag" @close="handleClose(index, scope.row)">{{ item }}</el-tag>
                <!-- 输入的文本框 -->
                <el-input v-if="scope.row.inputVisible" ref="saveTagInput" v-model="scope.row.inputValue" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" />
                <!-- 添加按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#" />
            <!--label="参数名称" 显示的标题-->
            <!--prop="attr_name"对应列内容的字段名-->
            <el-table-column label="参数名称" prop="attr_name" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="alterAttributes(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="delAttributes(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

      </el-tabs>

    </el-card>

    <!-- //^添加参数的弹出框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name" @keyup.enter.native="addConfirm" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- //^编辑参数的弹出框 -->
    <el-dialog
      title="编辑动态参数"
      :visible.sync="alterDialogVisible"
      width="50%"
      @close="alterDialogClosed"
    >
      <el-form ref="alterFormRef" :model="alterForm" :rules="alterFormRules" label-width="100px">
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="alterForm.attr_name" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="alterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alterconfirm ">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getCategoriesListNo } from '@/api/categories.js'
import {
  getAttributesList,
  putAttributes,
  addAttributes,
  delAttributes,
  getAttributesById
} from '@/api/params.js'

export default {
  name: 'Params',
  data() {
    return {
      // 选中的父级分类的Id数组
      selectedKeys: [],
      // 商品分类列表数据
      attributesList: [],
      // 配置数据显示的规则
      props: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },

      // ^tab面板
      // 被激活的页签的名称
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],

      // ^添加参数
      // 弹出框
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // ^编辑参数
      // 弹出框
      alterDialogVisible: false,
      // 添加参数的表单数据对象
      alterForm: {},
      // 表单验证规则
      alterFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },

  computed: {
    // ^添加按钮
    isBtnDisabled() {
      // 如果没有选择第三级分类，则禁止按钮
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // ^当前选中的三级分类的Id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // ^动态计算标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },

  created() {
    this.getAttributesList()
  },

  methods: {
    // ^获取商品分类列表
    async getAttributesList() {
      const res = await getCategoriesListNo()
      // console.log(res)
      this.attributesList = res
    },

    // ^下拉框
    // 当选中节点变化时触发
    handleChange() {
      // （封装）
      this.getParamsData()
    },

    // ^tab面板
    // 点击tab面板
    handleClick() {
      // （封装）
      this.getParamsData()
    },
    // 点击按钮，展示文本输入框
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      // this.$refs.saveTagInput.$refs.input.focus()
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //  点击输入框
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 输入了内容
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 编辑提交参数（封装）
      this.handleAttributes(row)
    },
    // tag关闭
    handleClose(index, row) {
      // 删除
      row.attr_vals.splice(index, 1)
      // 重新提交参数（封装）
      this.handleAttributes(row)
    },
    // #添加参数
    // 监听添加对话框的关闭事件
    addDialogClosed() {
      // 清空表单
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加参数/属性
    addConfirm() {
      this.$refs.addFormRef.validate(async valid => {
        // 验证不通过
        if (!valid) return
        // 验证通过,发起请求
        try {
          await addAttributes(
            this.cateId,
            this.addForm.attr_name,
            this.activeName
          )
          this.$message.success(`添加${this.titleText}成功！`)
          this.addDialogVisible = false
          this.getParamsData()
        } catch (err) {
          this.$message.error(`添加${this.titleText}失败！`)
        }
      })
    },
    // #删除参数
    async delAttributes(id) {
      // console.log(id)
      try {
        await delAttributes(this.cateId, id)
        this.$message.success('删除参数成功')
        this.getParamsData()
      } catch (err) {
        this.$message.error('删除参数失败')
      }
    },
    // #修改参数
    async alterAttributes(id) {
      // console.log(id)
      const res = await getAttributesById(this.cateId, id, this.activeName)
      // console.log(res)
      this.alterForm = res
      this.alterDialogVisible = true
    },
    // 重置修改的表单
    alterDialogClosed() {
      this.$refs.alterFormRef.resetFields()
    },
    // 修改确定提交参数
    async alterconfirm() {
      try {
        await putAttributes(this.cateId, this.alterForm.attr_id, {
          attr_name: this.alterForm.attr_name,
          attr_sel: this.alterForm.attr_sel
        })
        this.$message.success('修改参数项成功')
        this.alterDialogVisible = false
        this.getParamsData()
      } catch (err) {
        this.$message.error('修改参数项失败')
      }
    },

    // ^封装编辑提交参数
    async handleAttributes(row) {
      try {
        await putAttributes(this.cateId, row.attr_id, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        this.$message.success('修改参数项成功')
      } catch (err) {
        this.$message.error('修改参数项失败')
      }
      // console.log(res)
    },

    // ^封装获取参数的列表数据
    async getParamsData() {
      // 如果selectedKeys数组的长度不是3，代表选择的不是第三极，
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 选择的是第三极，则发起请求
      // const cateId = this.selectedKeys[2]
      const res = await getAttributesList(this.cateId, this.activeName)
      // console.log(res)
      // 处理数据
      res.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 添加一个控制文本框的显示与隐藏的属性
        item.inputVisible = false
        // 加一个文本框中输入的值的属性
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res
      } else {
        this.onlyTableData = res
      }
    }
  }
}
</script>

<style scoped lang='less'>
.cascader {
  margin: 20px 0;
}
.tag {
  margin-right: 7px;
}
</style>
